﻿using Newtonsoft.Json;
using SocialKit.LightRest;
using Newtonsoft.Json.Linq;

namespace SocialKit.QQPengyou
{
    /// <summary>
    /// HTTP 响应消息扩展类。
    /// </summary>
    static class HttpResponseMessageExtensions
    {
        /// <summary>
        /// 读取 JSON 数据为指定的类型。
        /// </summary>
        /// <typeparam name="T">要转换的类型。</typeparam>
        /// <param name="response">HTTP 响应消息。</param>
        /// <returns></returns>
        public static T ReadJsonContent<T>(this HttpResponseMessage response)
        {
            if (response == null)
                return default(T);

            return JsonConvert.DeserializeObject<T>(response.ReadContentAsString());
        }

        /// <summary>
        /// 读取 JSON 数据。
        /// </summary>
        /// <param name="response">HTTP 响应消息。</param>
        /// <returns></returns>
        public static object ReadJsonContent(this HttpResponseMessage response)
        {
            if (response == null)
                return null;

            return JsonConvert.DeserializeObject(response.ReadContentAsString());
        }

        /// <summary>
        /// 确保返回的是正确的，否则抛出异常。
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static HttpResponseMessage Ensure(this HttpResponseMessage response)
        {
            response.LoadContentIntoBuffer();

            var json = ReadJsonContent(response) as JObject;

            if (json["ret"].ToString() != "0")
                throw new PengyouException(int.Parse(json["ret"].ToString()), json["msg"].ToString());

            return response;
        }
    }
}